package by.epam.communalservices.connection;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


import by.epam.communalservices.connection.JdbcConnection;
import by.epam.communalservices.exception.JkhDaoException;


public class DbConnection implements JdbcConnection {
    private Connection conn;

    private Properties props = new Properties();

    public void close() throws JkhDaoException {
        try {
            conn.close();
        } catch (SQLException ex) {
            throw new JkhDaoException("Failed to close", ex);
        }
        System.out.println("Connection closed...");
    }

    public void connect() throws JkhDaoException {
        initDriver();
        try {
            conn = DriverManager.getConnection(props.getProperty("jdbc.url"),
                    props.getProperty("jdbc.username"),
                    props.getProperty("jdbc.password"));
        } catch (SQLException ex) {
            throw new JkhDaoException("Connection Error", ex);
        }
    }

    public Connection getConnection() {
        if (conn != null) {
            return conn;
        } else {
            return null;
        }
    }

    public void setConnection(InputStream in) throws JkhDaoException {
        try {
            props.load(in);
            in.close();
        } catch (IOException ex) {
            throw new JkhDaoException(
                    "Error while setting connection properties", ex);
        }
        setConnection(props.getProperty("jdbc.drivers"),
                props.getProperty("jdbc.url"),
                props.getProperty("jdbc.username"),
                props.getProperty("jdbc.password"));
    }

    public void setConnection(String drivers, String url, String username,
            String password) {
        props.setProperty("jdbc.drivers", drivers);
        props.setProperty("jdbc.url", url);
        props.setProperty("jdbc.username", username);
        props.setProperty("jdbc.password", password);

    }

    public void initDriver() throws JkhDaoException {
        try {
            Class.forName(props.getProperty("jdbc.drivers"));
        } catch (ClassNotFoundException ex) {
            throw new JkhDaoException("Error initializing driver", ex);
        }
    }

}
